import URLs from "@/config/url.js";
import { logout, login } from '@/utils/login.js'
import { showLoginPopup } from '@/utils/login.js'
import store from '@/store/index.js'

// 可重复请求的白名单
const whiteList = [''];
// 校验重复请求的方法
const checkRepeat = checkRepeatRequest()

/**
 * 请求数据封装方法
 * @param method 请求方式 GET POST PUT
 * @param url 请求地址（login/login）
 * @param data 请求数据
 * @param loading 是否展示loading
 * @param loadingTitle 展示loading文字
 * @returns {Promise<unknown>}
 */
function request(method, url, data, loading = false, loadingTitle = "loading……", loadingMask = true) {
	// 校验是否是重复请求
	checkRepeat(url).catch(err => {
		uni.showToast({
			icon: 'none',
			title: 'Operate too frequently~'
		})
		return Promise.reject()
	})
	
	loading && uni.showLoading({
		title: loadingTitle,
		mask: loadingMask
	})
	const header = {
		'content-type': 'application/json;charset=UTF-8',
	}
	if(uni.getStorageSync('token')){
		header.Authorization = uni.getStorageSync('token')
	}
	return new Promise((resolve, reject) => {
		//发起请求
		uni.request({
			url: URLs.host + '/'+ url,
			method,
			data,
			header,
			success: res => {
				loading && uni.hideLoading()
				let code = res.data.code
				let message = res.data.msg || 'server error';
				// 请求成功
				if(code == 200){
					resolve(res.data)
				}
				// 未授权 || 授权已过期
				else if(code == 401 || code == 403){
					store.commit('user/SET_TOKEN', '')
					store.commit('user/SET_LOGIN', false);
					store.commit('user/SET_USERID', '');
					showLoginPopup(1)
					reject()
				}
				// 用户被停用
				else if(code == 402){
					store.commit('user/SET_LOGIN', false);
					store.commit('user/SET_TOKEN', "");
					store.commit('user/SET_USERID', "");
					showLoginPopup(2)
					reject()
					
				}
				// 错误
				else if(code == 500){
					uni.showToast({
						icon: 'none',
						title: message
					})
					reject(message)
				}
				// 业务处理失败
				else if(code == 601){
					resolve(res.data, message)
				}
			},
			fail: err => {
				loading && uni.hideLoading()
				uni.showToast({
					icon: 'none',
					title: 'Request time out!'
				})
				reject(err)
			}
		});
	})
}

/**
 * 校验是否是重复请求
 * @param {Object} url
 */
function checkRepeatRequest(){
	// 上次请求地址
	let beforeReq = '';		
	// 上次请求时间
	let beforeReqTime = 0	
	// 判断重复请求的计算时间 单位:ms
	const betweenTime = 500 
	
	return function(url){
		const nowTime = new Date().getTime()
		// 不在白名单内，且此次请求与上次请求一致且间隔时间小于300毫秒视为重复请求
		if(whiteList.indexOf(url) == -1 && url == beforeReq && nowTime - beforeReqTime < betweenTime){
			console.log('本次请求与上次请求重复，本次请求:' + url + '，上次请求:' + beforeReq);
			beforeReq = url
			beforeReqTime = nowTime
			return Promise.reject()
		}
		// 正常请求
		else{	
			beforeReq = url
			beforeReqTime = nowTime
			return Promise.resolve()
		}
	}
}

let requests = {}
const types = ['get', 'post', 'put', 'delete']
types.forEach(item => {
	requests[item] = function (url, params, loading, loadingTitle){
		return request(item, url, params, loading, loadingTitle)
	}
})

export default requests
